<?php
// 设置允许的来源
header("Access-Control-Allow-Origin: http://localhost:9528");

// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "../conn.php";
require_once "../usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, "Msg" => "连接错误: " . $conn->connect_error]));
}



$zhongkongName = $username;

// 获取前端传递的 JSON 数据
$data = json_decode(file_get_contents("php://input"), true);

// 获取参数
$sort = isset($data['sort']) ? $data['sort'] : '在线';
$currentPage = isset($data['currentPage']) ? intval($data['currentPage']) : 1;
$pageSize = isset($data['pagesize']) ? intval($data['pagesize']) : 25;
$total = isset($data['total']) ? intval($data['total']) : 0;
$deviceName = isset($data['deviceName']) ? $data['deviceName'] : '';
$pollcode = isset($data['pollcode']) ? $data['pollcode'] : '';
$state = isset($data['state']) ? $data['state'] : '全部';
$scriptState = isset($data['scriptState']) ? $data['scriptState'] : ['全部状态'];
$ids = isset($data['Id']) ? $data['Id'] : [];

// 防止SQL注入，对每个ID进行转义
$safeIds = array_map(function ($id) use ($conn) {
    return "'" . $conn->real_escape_string($id) . "'";
}, $ids);

// 构建SQL查询语句
$sql = "SELECT d.*, dg.group_name 
        FROM devices d 
        LEFT JOIN device_groups dg ON d.group_id = dg.id 
        WHERE 1=1";

if (!empty($safeIds)) {
    $sql .= " AND d.id IN (" . implode(',', $safeIds) . ")";
}

if ($state !== '全部') {
    $sql .= " AND d.running_status = '" . $conn->real_escape_string($state) . "'";
}

if ($deviceName) {
    $sql .= " AND d.device_name LIKE '%" . $conn->real_escape_string($deviceName) . "%'";
}

if ($pollcode) {
    $sql .= " AND d.registration_code = '" . $conn->real_escape_string($pollcode) . "'";
}

if ($scriptState[0] !== '全部状态') {
    $sql .= " AND d.running_status IN ('" . implode("', '", array_map([$conn, 'real_escape_string'], $scriptState)) . "')";
}

// 过滤中控账号
$sql .= " AND (d.zhongkong_name = '" . $conn->real_escape_string($zhongkongName) . "' OR dg.zhongkong_name = '" . $conn->real_escape_string($zhongkongName) . "')";

$sql .= " ORDER BY dg.sort DESC, d.id";

// 分页
$offset = ($currentPage - 1) * $pageSize;
$sql .= " LIMIT $offset, $pageSize";

$result = $conn->query($sql);

$devices = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }
}

// 获取总记录数
$totalSql = str_replace("LIMIT $offset, $pageSize", "", $sql);
$totalResult = $conn->query($totalSql);
$totalCount = $totalResult->num_rows;

// 分组
$groups = [];
$defaultGroup = ['groupName' => '默认分组', 'device' => []];

foreach ($devices as $device) {
    if ($device['group_name']) {
        if (!isset($groups[$device['group_name']])) {
            $groups[$device['group_name']] = ['groupName' => $device['group_name'], 'device' => []];
        }
        $groups[$device['group_name']]['device'][] = ['Id' => $device['id'], 'dev_name' => $device['device_name']];
    } else {
        $defaultGroup['device'][] = ['Id' => $device['id'], 'dev_name' => $device['device_name']];
    }
}

if (!empty($defaultGroup['device'])) {
    $groups['默认分组'] = $defaultGroup;
}

// 计算在线和离线数量
$onlineNum = 0;
$offlineNum = 0;
foreach ($devices as $device) {
    if ($device['running_status'] === '在线') {
        $onlineNum++;
    } else {
        $offlineNum++;
    }
}

// 返回结果
echo json_encode([
    "code" => 1,
    "msg" => "获取成功",
    "data" => [
        "total" => $totalCount,
        "pagesize" => $pageSize,
        "data" => array_map(function ($device) {
            // 假设根据设备ID生成 bindingScriptConfigId 和 bindingScriptConfigName
            $bindingScriptConfigId = $device['id'] * 100; // 示例逻辑
            $bindingScriptConfigName = "ScriptConfig" . $device['id']; // 示例逻辑
            return [
                "Id" => $device['id'],
                "dev_name" => $device['device_name'],
                "pollcode" => $device['registration_code'],
                "realname" => $device['realname'] ?? "",
                "state" => $device['enabled'] ?? 1,
                "bindingScriptConfigId" => $bindingScriptConfigId,
                "bindingScriptConfigName" => $bindingScriptConfigName,
                "version" => $device['version'] ?? "未知",
                "online" => $device['running_status'] === '在线' ? 1 : 0,
                "scriptState" => $device['running_status'],
                "switch_data" => $device['switch_data'] ?? "",
            ];
        }, $devices),
        "group" => array_values($groups),
        "onlineNum" => $onlineNum,
        "offlineNum" => $offlineNum,
    ]
]);
